package api

import (
	"time"

	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
	"zhonghui/console/service"
	"zhonghui/console/structs"
	"zhonghui/console/warehouse/dbx/cache_main"
	"zhonghui/console/warehouse/helperx"
	"zhonghui/console/warehouse/respx"
)

func (server *Server) GetAnalysis(c *gin.Context) {
	resp := structs.GetAnalysisResp{}

	ca := cache_main.Client().Get(c, "analysis_dashboard").Val()
	if ca != "" {
		jsoniter.UnmarshalFromString(ca, &resp)
		respx.Success(c, resp, nil)
		return
	}

	// 总计短信个数
	totalSms := service.GetTotalSmsCharts()
	resp.Count = uint64(totalSms.Total)
	resp.CountFail = uint64(totalSms.Fail)
	if resp.Count > 0 {
		resp.FailRate = helperx.NiceRate(float64(resp.CountFail) / float64(resp.Count))
	} else {
		resp.FailRate = "0%"
	}

	// 点击数据
	resp.ClickCharts = service.GetTotalClickData()
	if resp.Count > 0 {
		resp.ClickCharts.ClickRate = helperx.NiceRate(float64(resp.ClickCharts.Total) / float64(resp.Count))
	} else {
		resp.ClickCharts.ClickRate = "0%"
	}

	// 小程序数据
	resp.MpCharts = service.GetTotalMpData()
	if resp.ClickCharts.Total > 0 {
		resp.MpCharts.MpRate = helperx.NiceRate(float64(resp.MpCharts.Total) / float64(resp.ClickCharts.Total))
	} else {
		resp.MpCharts.MpRate = "0%"
	}

	// 企微数据
	resp.WeComCharts = service.GetTotalWeComData()
	if resp.MpCharts.Total > 0 {
		resp.WeComCharts.WeComRate = helperx.NiceRate(float64(resp.WeComCharts.Total) / float64(resp.MpCharts.Total))
	} else {
		resp.WeComCharts.WeComRate = "0%"
	}

	// 投保成功页面访问
	resp.InsurancePolicyCharts = service.GetTotalInsurancePolicyData()
	if resp.ClickCharts.Total > 0 {
		resp.InsurancePolicyCharts.PolicyRate = helperx.NiceRate(float64(resp.InsurancePolicyCharts.Total) / float64(resp.ClickCharts.Total))
	} else {
		resp.InsurancePolicyCharts.PolicyRate = "0%"
	}

	resp.AreaCharts = service.GetTotalUserAreaData()
	resp.DeviceCharts = service.GetTotalUserDeviceData()
	resp.UserCharts = service.GetTotalUserSummary()

	// 一些假数据
	visitArr := `[{"key": "2023-02-15","value": 7},{"key": "2023-02-16","value": 5},{"key": "2023-02-17","value": 4},{"key": "2023-02-18","value": 2},{"key": "2023-02-19","value": 4},{"key": "2023-02-20","value": 7},{"key": "2023-02-21","value": 5},{"key": "2023-02-22","value": 6},{"key": "2023-02-23","value": 5},{"key": "2023-02-24","value": 9},{"key": "2023-02-25","value": 6},{"key": "2023-02-26","value": 3},{"key": "2023-02-27","value": 1},{"key": "2023-02-28","value": 5},{"key": "2023-03-01","value": 3},{"key": "2023-03-02","value": 6},{"key": "2023-03-03","value": 5}]`
	visitList := make([]structs.ChartsKV, 0)
	_ = jsoniter.UnmarshalFromString(visitArr, &visitList)
	resp.VisitData = visitList

	j, _ := jsoniter.MarshalToString(resp)
	cache_main.Client().Set(c, "analysis_dashboard", j, time.Minute*5)

	respx.Success(c, resp, nil)
}
